import { create } from 'zustand'

interface AIMessage {
  id: string
  role: 'user' | 'assistant' | 'system'
  content: string
  timestamp: string
  sessionId: string
}

interface AIScenario {
  id: string
  name: string
  description: string
  icon: string
}

interface AIRole {
  id: string
  name: string
  description: string
  style: string
}

interface AIModel {
  id: string
  name: string
  description: string
  pricing: string
}

interface AIStore {
  messages: AIMessage[]
  scenarios: AIScenario[]
  roles: AIRole[]
  models: AIModel[]
  currentSessionId: string
  loading: boolean
  error: string | null
  
  // Actions
  sendMessage: (message: string, scenario?: string, role?: string) => Promise<void>
  generateContent: (type: string, prompt: string) => Promise<void>
  loadHistory: (sessionId: string) => Promise<void>
  loadScenarios: () => Promise<void>
  loadRoles: () => Promise<void>
  loadModels: () => Promise<void>
  clearHistory: (sessionId: string) => Promise<void>
  setSessionId: (sessionId: string) => void
  getUsage: () => Promise<any>
  testConnection: () => Promise<boolean>
}

export const useAIStore = create<AIStore>((set, get) => ({
  messages: [],
  scenarios: [
    { id: 'general', name: '通用对话', description: '日常问答和帮助', icon: 'chat' },
    { id: 'family-planning', name: '家族规划', description: '家族活动规划和建议', icon: 'calendar' },
    { id: 'tradition', name: '传统咨询', description: '家族传统和文化相关咨询', icon: 'history' },
    { id: 'conflict-resolution', name: '矛盾调解', description: '家族矛盾调解建议', icon: 'handshake' },
    { id: 'education', name: '教育指导', description: '家族后代教育建议', icon: 'graduation-cap' }
  ],
  roles: [
    { id: 'elder', name: '家族长者', description: '以家族长辈的身份提供建议', style: 'wise, traditional, authoritative' },
    { id: 'mediator', name: '调解员', description: '以中立调解员的身份处理问题', style: 'neutral, diplomatic, solution-oriented' },
    { id: 'historian', name: '历史学家', description: '以历史学家的视角提供建议', style: 'scholarly, detailed, context-aware' },
    { id: 'counselor', name: '顾问', description: '以专业顾问的身份提供指导', style: 'professional, strategic, forward-looking' }
  ],
  models: [],
  currentSessionId: 'default',
  loading: false,
  error: null,

  sendMessage: async (message, scenario, role) => {
    const sessionId = get().currentSessionId
    const tempMessage = {
      id: Date.now().toString(),
      role: 'user' as const,
      content: message,
      timestamp: new Date().toISOString(),
      sessionId
    }
    
    set((state) => ({
      messages: [...state.messages, tempMessage],
      loading: true,
      error: null
    }))

    try {
      const response = await fetch('/api/ai/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          message,
          sessionId,
          scenario,
          role
        }),
      })
      
      const data = await response.json()
      if (data.success) {
        const aiMessage = {
          id: (Date.now() + 1).toString(),
          role: 'assistant' as const,
          content: data.data.response,
          timestamp: new Date().toISOString(),
          sessionId
        }
        set((state) => ({
          messages: [...state.messages, aiMessage],
          loading: false
        }))
      }
    } catch (error: any) {
      set({
        loading: false,
        error: error.message || 'AI服务暂不可用'
      })
    }
  },

  generateContent: async (type, prompt) => {
    const sessionId = `content-${Date.now()}`
    set({ loading: true, error: null })
    
    try {
      const response = await fetch('/api/ai/generate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ type, prompt }),
      })
      
      const data = await response.json()
      if (data.success) {
        const contentMessage = {
          id: Date.now().toString(),
          role: 'assistant' as const,
          content: data.data.content,
          timestamp: new Date().toISOString(),
          sessionId
        }
        set((state) => ({
          messages: [...state.messages, contentMessage],
          loading: false
        }))
      }
    } catch (error: any) {
      set({
        loading: false,
        error: error.message || '内容生成失败'
      })
    }
  },

  loadHistory: async (sessionId) => {
    try {
      const response = await fetch(`/api/ai/chat/history?sessionId=${sessionId}`)
      const data = await response.json()
      if (data.success) {
        const historyMessages = data.data.data?.reverse().map((msg: any) => ({
          id: msg.id.toString(),
          role: msg.role || (msg.message ? 'user' : 'assistant'),
          content: msg.message || msg.response,
          timestamp: msg.createdAt,
          sessionId: msg.sessionId
        })) || []
        set({ messages: historyMessages })
      }
    } catch (error: any) {
      set({ error: error.message })
    }
  },

  loadScenarios: async () => {
    try {
      const response = await fetch('/api/ai/scenarios')
      const data = await response.json()
      if (data.success) {
        set({ scenarios: data.data })
      }
    } catch (error: any) {
      set({ error: error.message })
    }
  },

  loadRoles: async () => {
    try {
      const response = await fetch('/api/ai/roles')
      const data = await response.json()
      if (data.success) {
        set({ roles: data.data })
      }
    } catch (error: any) {
      set({ error: error.message })
    }
  },

  loadModels: async () => {
    try {
      const response = await fetch('/api/ai/models')
      const data = await response.json()
      if (data.success) {
        set({ models: data.data })
      }
    } catch (error: any) {
      set({ error: error.message })
    }
  },

  clearHistory: async (sessionId) => {
    try {
      const response = await fetch('/api/ai/chat/history', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ sessionId })
      })
      const data = await response.json()
      if (data.success) {
        set({ messages: [] })
      }
    } catch (error: any) {
      set({ error: error.message })
    }
  },

  setSessionId: (sessionId) => {
    set({ currentSessionId: sessionId })
  },

  getUsage: async () => {
    try {
      const response = await fetch('/api/ai/usage')
      const data = await response.json()
      return data.data
    } catch (error: any) {
      set({ error: error.message })
      return null
    }
  },

  testConnection: async () => {
    try {
      const response = await fetch('/api/ai/test', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
      })
      const data = await response.json()
      return data.success && data.data.connected
    } catch (error) {
      return false
    }
  }
}))